package com.sanjiahantang.youjiaclient.module.category.views.impl;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;


import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseMvpFragment;
import com.sanjiahantang.youjiaclient.http.OkHttpClientManager;
import com.sanjiahantang.youjiaclient.module.category.adapters.CategoryTopAdapter;
import com.sanjiahantang.youjiaclient.module.category.beans.CategoryBean;
import com.sanjiahantang.youjiaclient.module.category.presenters.CategoryPresenter;
import com.sanjiahantang.youjiaclient.module.category.views.CategoryView;

import java.util.ArrayList;
import java.util.List;


public class CategoryFragment extends BaseMvpFragment<CategoryView,CategoryPresenter> implements
        CategoryView,
        AdapterView.OnItemClickListener,
        View.OnClickListener {


    private LinearLayout mMainContent;

    private ViewStub mNetworStub;
    private View mNetworkErrorLayout;
    private Button mReloadRequest;            //网络错误k

    private EditText mSearch;    //搜索框

    //--------------- 一级列表 ----------------------
    private ListView mOneListView;
    private CategoryTopAdapter mOneAdapter;
    private List<CategoryBean.Info> mOneData;


    //--------------- 二级列表 ----------------------
    private FragmentManager mFragmentManager;
    private FragmentTransaction mft;
    private View back;
    private TextView title;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mFragmentManager = getChildFragmentManager();
    }

    private View rootView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.fragment_category, container, false);
            initToolbar(rootView);

            mNetworStub = (ViewStub) rootView.findViewById(R.id.vsNetworkError);
            mMainContent = (LinearLayout) rootView.findViewById(R.id.mainContents);

            initOneCategory(rootView);
            presenter.loadCategoryByType(getActivity(), CategoryView.ONE_LEVEL, null);
        }


        return rootView;
    }

    @Override
    public CategoryPresenter initPresenter() {
        return new CategoryPresenter();
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {


        switch (v.getId()) {
            case R.id.btnReloadNetwork:        //重新加载网络

                presenter.loadCategoryByType(getContext(), CategoryView.ONE_LEVEL, null);

                break;
            case R.id.back:
                getActivity().finish();
                break;
        }
    }


    private void initToolbar(View v) {
        title = (TextView) rootView.findViewById(R.id.title);
        back = rootView.findViewById(R.id.back);

        title.setText("分类");
        back.setOnClickListener(this);
    }


    /**
     * 初始化一级列表
     *
     * @param v
     */
    private void initOneCategory(View v) {
        mOneListView = (ListView) v.findViewById(R.id.lvOneLevel);
        mOneListView.setOnItemClickListener(this);


        mOneAdapter = new CategoryTopAdapter(getActivity(), R.layout.item_category_level_1);
        mOneListView.setAdapter(mOneAdapter);

    }


    /**
     * 一级 分类回调
     *
     * @param data
     */

    public void onOneLevelData(CategoryBean data, @Nullable Exception e) {

        if (e != null) {

            switchLayout();
            return;
        }

        if (data == null) return;

        if (mNetworkErrorLayout != null) {

            mNetworkErrorLayout.setVisibility(View.GONE);
        }

        mMainContent.setVisibility(View.VISIBLE);

        if (mOneData == null) {
            mOneData = new ArrayList<>();
        }
        mOneData.clear();
        mOneAdapter.clear();

        /*data.getData().getClassify().get(currPosition).setChecked(true); //第一个默认选中
        mOneData.addAll(data.getData().getClassify());

        mOneAdapter.addAll(this.mOneData);

        checkCacheWithLoad(currPosition, Integer.valueOf(data.getData().getClassify().get(currPosition).getClassify_id()));*/

//		mPresenter.loadCategoryByType(getContext(),CategoryPresenter.TWO_LEVEL,);

    }

    /**
     * 二级分类回调
     *
     * @param data
     */

    public void onTwoLevelData(CategoryBean.Data data, @Nullable Exception e) {

        if (e != null) {

            switchLayout();
            return;
        }

        if (mNetworkErrorLayout != null) {

            mNetworkErrorLayout.setVisibility(View.GONE);
        }

        mMainContent.setVisibility(View.VISIBLE);

        if (data != null) {

            mFragmentManager.beginTransaction()
                    .replace(R.id.contents, CategorySubFragment.newInstance(data))
                    .commitAllowingStateLoss();

//			mFragmentManager.beginTransaction()
//					.replace(R.id.contents, CategorySubFragment.newInstance(data))
//					.commit();
        }


    }


    public void switchLayout() {

        if (mNetworkErrorLayout == null) {

            mNetworkErrorLayout = mNetworStub.inflate();
            mReloadRequest = (Button) mNetworkErrorLayout.findViewById(R.id.btnReloadNetwork);

            mReloadRequest.setOnClickListener(this);

        } else {
            mNetworkErrorLayout.setVisibility(View.VISIBLE);

        }

        mMainContent.setVisibility(View.GONE);


    }


    private int currPosition;
    private TextView currItemView;

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        OkHttpClientManager.cancelTag(getContext(), "category" + CategoryView.ONE_LEVEL);
//        OkHttpClientManager.cancelTag(getContext(), mPresenter.getTag());
    }

    /**
     * 一级item点击事件
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        if (currPosition == position) {
            return;
        }


        mOneData.get(currPosition).setChecked(false);
        mOneData.get(position).setChecked(true);

        currPosition = position;

        mOneAdapter.notifyDataSetChanged();

        if (android.os.Build.VERSION.SDK_INT >= 11) {

            mOneListView.smoothScrollToPositionFromTop(position, 0);
        } else {
            mOneListView.setSelectionFromTop(position, 0);
        }

//        mPresenter.loadCategoryByType(getContext(), CategoryPresenter.TWO_LEVEL, Integer.valueOf(mOneData.get(currPosition).getClassify_id()));

    }

    /**
     * 判断缓存中是否已经存在
     */
    private void checkCacheWithLoad(int key, int id) {

        //判断个 JJ 啊，我已经删了。。。。。

//        mPresenter.loadCategoryByType(getActivity(), CategoryPresenter.TWO_LEVEL, id);


    }


    @Override
    public void showProgress() {
        context.showProgress(context);
    }

    @Override
    public void hideProgress() {
        context.hideProgress();
    }
}
